/*
   Licensed to the Apache Software Foundation (ASF) under one
   or more contributor license agreements.  See the NOTICE file
   distributed with this work for additional information
   regarding copyright ownership.  The ASF licenses this file
   to you under the Apache License, Version 2.0 (the
   "License"); you may not use this file except in compliance
   with the License.  You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing,
   software distributed under the License is distributed on an
   "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
   KIND, either express or implied.  See the License for the
   specific language governing permissions and limitations
   under the License. 
*/

package com.google.enterprise.gsa.crf;

import java.io.IOException;
import javax.servlet.http.*;
import javax.jdo.PersistenceManager;
import java.util.List;
import java.io.*;
import javax.jdo.Query;

public class CRFDataSource extends HttpServlet {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@SuppressWarnings("unchecked")
	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		String reportName = "report";
        String value = req.getParameter(reportName);
        PrintWriter out = resp.getWriter();
		PersistenceManager pm = PMF.get().getPersistenceManager();
		
        if (value == null) {
        	out.println("Wrong call to datasource Servlet");
        } else if ("wc".equals(value)){
    		String theResponse = "";

    		resp.setContentType("text/plain");
    		    		
    		theResponse = "google.visualization.Query.setResponse(";
    		theResponse += "{version:'0.5',reqId:'0',status:'ok',sig:'0',table:";
    		theResponse +="{cols:[{id:'words',label:'',type:'string',pattern:''}],";
    		theResponse +="rows:[";
    		
            String query = "select from " + DBClickRecord.class.getName() + " order by date desc";
            
            List<DBClickRecord> records = (List<DBClickRecord>) pm.newQuery(query).execute();
            if (records.isEmpty()) {
            } else {
            	//out.println("dataRequests.addRows(" + records3.size() + ");");

            	for (DBClickRecord cr : records) {     
            		theResponse += "{c:[{v:'" + cr.getQ() + "'}]}";
            		if(!records.isEmpty()) theResponse += ",";
                }
            }
            theResponse += "]}});";
            pm.close();

    		resp.getWriter().println(theResponse);
        } else if("cpr".equals(value)) {    		
    		resp.setContentType("text/plain");
    		
    		String theResponse = "google.visualization.Query.setResponse({version:'0.5',reqId:'0',status:'ok',sig:'0',table:{";
    		theResponse += "cols: ";
    		theResponse += DBClicksPerRow.JSONColumns() + ",rows: [";
    		    		
            String query = "select from " + DBClicksPerRow.class.getName();
            
            List<DBClicksPerRow> records = (List<DBClicksPerRow>) pm.newQuery(query).execute();
            if (records.isEmpty()) {
            } else {
            	for (DBClicksPerRow cpr : records) {     
            		theResponse += cpr.toJSON();
            		if(!records.isEmpty()) theResponse += ",";
                }
            }
            theResponse += "]}});";
            pm.close();
    		resp.getWriter().println(theResponse);
        } else if("qf".equals(value)){    		
    		resp.setContentType("text/plain");
    		
    		String theResponse = "google.visualization.Query.setResponse({version:'0.5',reqId:'0',status:'ok',sig:'0',table:{";
    		theResponse += "cols: ";
    		theResponse += DBQueryFrequency.JSONColumns() + ",rows: [";
    		    		
            String query = "select from " + DBQueryFrequency.class.getName() + " order by frequency desc";
            Query theQuery = pm.newQuery(query);
        	theQuery.setRange(0,10);
            
            List<DBQueryFrequency> records = (List<DBQueryFrequency>) theQuery.execute();
            if (records.isEmpty()) {
            } else {
            	for (DBQueryFrequency qf : records) {     
            		theResponse += qf.toJSON();
            		if(!records.isEmpty()) theResponse += ",";
                }
            }
            theResponse += "]}});";
            pm.close();
    		resp.getWriter().println(theResponse);
        } else if("q".equals(value)){
    		resp.setContentType("text/plain");
    		
    		String theResponse = "google.visualization.Query.setResponse({version:'0.5',reqId:'0',status:'ok',sig:'0',table:{";
    		theResponse += "cols: ";
    		theResponse += DBClickRecord.JSONColumns() + ",rows: [";
    		    		
            String query = "select from " + DBClickRecord.class.getName() + " order by date desc";
            Query theQuery = pm.newQuery(query);
        	theQuery.setRange(0,20);
            
            List<DBClickRecord> records = (List<DBClickRecord>) theQuery.execute();
            if (records.isEmpty()) {
            } else {
            	for (DBClickRecord q : records) {     
            		theResponse += q.toJSON();
            		if(!records.isEmpty()) theResponse += ",";
                }
            }
            theResponse += "]}});";
            pm.close();
    		resp.getWriter().println(theResponse);        	
        }
        else{
        	out.println("Wrong report name");
        }
        out.close();
	}
}
